<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Exception\XZXValidationException;
use App\Service\CommissionSalesService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Contract\TranslatorInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Middleware\AdminApi\NodeAccessMiddleware;

/**
 * Class CommissionSaleController
 * @package App\Controller
 * @Controller(prefix="/admin/api/commissionSales")
 */
class CommissionSalesController extends AdminBaseController
{
    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var CommissionSalesService
     */
    protected $CommissionSalesService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale()
    {
        if($this->request->header('locale') == 'en')
        {
            $this->translator->setLocale('en');
        }
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->CommissionSalesService->get($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page' => 'required|integer|min:1',
                'limit' => 'required|integer|min:1',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'salesId');
            CustomUtils::xzxAddSearch($param, $search, 'statMonth');
            if(isset($search["statMonth"]))
            {
                if (!empty($search["statMonth"])) {
                    $param['statMonth'][0] = $param['statMonth'][0];
                    $param['statMonth'][1] = $param['statMonth'][1];
                } else {
                    unset($param['statMonth']);
                }
            }
        }

        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            // 这里需要处理，如果是一级，就用mchIdList去查就行，因为这里包括了二级的数据
            // 如果是二级，就用salesId去查，这样才能查到属于自己的数据
            $user = $ext['user'];
            $role = $ext['role'];
            if ($user['level'] == 1 && $role['extraType'] == 1) {
                // 一级销售
                $param['mchIdList'] =  $ext['mchIdList'];
            } else if ($user['level'] == 2 && $role['extraType'] == 1) {
                $param['salesId'] =  $ext['uid'];
            } else {
                $param['mchIdList'] =  $ext['mchIdList'];
            }
        }

        return $this->CommissionSalesService->list($param);
    }

    /**
     * 绑定商户
     * @PostMapping(path = "bindMch")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     */
    public function bindMch(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'mchEmail' => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid'] = $ext['uid'];
        return $this->CommissionSalesService->bindMch($param);
    }

    /**
     * 获取已绑定商户
     * @PostMapping(path = "getBindedMch")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getBindedMch(RequestInterface $request)
    {
        $this->setlocale();

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid'] = $ext['uid'];
        return $this->CommissionSalesService->getBindedMch($param);
    }

}
